package com.xy.blog.article.domain.service.impl.anchor;

import com.xy.blog.article.domain.service.IAnchorService;
import com.xy.blog.article.domain.service.model.AnchorBO;
import com.xy.blog.article.domain.utils.MarkdownUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author zanhonglei
 * @version V1.0
 * @Description:
 * @date 2020/5/31
 */
@Service
public class MarkDownAnchorServiceImpl implements IAnchorService {

    /**
     * 生成锚点核心方法
     * @param contentMd
     * @return
     */
    @Override
    public List<AnchorBO> generateAnchor(String contentMd) {
        String s = MarkdownUtils.markdownToHtmlExtensions(contentMd);
        Document parse = Jsoup.parse(s);
        Element body = parse.body();
        Elements elementsByClass = body.getElementsByClass("xy-anchor");
        List<AnchorBO> list = new ArrayList<>();
        Iterator<Element> iterator = elementsByClass.iterator();
        int preLevel = 1;
        while (iterator.hasNext()) {
            Element element = iterator.next();
            int tagLevel = Integer.parseInt(element.attr("tag_level"));
            String text = element.text();
            String href = text.toLowerCase().replace(" ", "-");
            AnchorBO anchorBO = new AnchorBO();
            anchorBO.setHref(href);
            anchorBO.setTitle(text);
            if (tagLevel > preLevel) {
                // 继续添加该深度
                int max = Math.max((list.size() - 1), 0);
                AnchorBO point = max == 0 ? anchorBO : list.get(max);
                if (point == null) {
                    point = anchorBO;
                    list.add(point);
                    continue;
                }
                List<AnchorBO> children = new ArrayList<>();
                while (point.getChildren() != null) {
                    List<AnchorBO> childrenPoint = point.getChildren();
                    point = childrenPoint.get(childrenPoint.size() - 1);
                }
                children.add(anchorBO);
                point.setChildren(children);
            } else  {
                // 同级 或者 重新创建一个新的链表
                list.add(anchorBO);
            }
            preLevel = tagLevel;

        }
        return list;
    }
}
